<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="./common.css" rel="stylesheet" type="text/css" />
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #container {
            width: 100vw;
            height: 100vh;
        }
        
        .header {
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .header input {
            width: 75%;
        }
        
        .user-postion {
            display: block;
            width: 32px;
            height: 32px;
            position: fixed;
            right: 50px;
            bottom: 50px;
            z-index: 1000;
        }
    </style>
</head>

<body>
    <div id="container"></div>

    <img src="./img/position-icon.png" alt="" class="user-postion">
    <div class="header">
        <span class="changeCity"></span>
        <input type="text" id="search" autocomplete="off" class="startInput">
    </div>

    <script type="text/javascript" src='//webapi.amap.com/maps?v=2.0&key=31625f6bd617e01a2d06ef32b2033d35&plugin=AMap.ToolBar'></script>
    <script src="https://webapi.amap.com/maps?v=1.4.15&key=31625f6bd617e01a2d06ef32b2033d35"></script>
    <!-- UI组件库 1.0 -->
    <script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>
    <script src="./common.js"></script>
    <script>
        let pos = [106.506807, 29.535172]
        let positions = []
        for (var i = 0; i < 100; i++) {

            positions.push([pos[0] + Math.random() * 0.1, pos[1] + Math.random() * 0.05])

        }


        var center = '';
        // 地图初始化
        const map = new AMap.Map('container', {
            zoom: 12,
            resizeEnable: true,
            rotateEnable: true,
            pitchEnable: true,
            pitch: 80,
            buildingAnimation: true, //楼块出现是否带动画
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            expandZoomRange: true,
            zooms: [3, 20],
        });


        if (!AMap.UA.mobile) {
            var div = document.createElement('div');
            div.className = 'noti-tip';

            div.innerHTML = '请在手机模式下查看本页面';

            document.body.appendChild(div);
        }
        // 经纬度 地址信息
        var mapInfo = {
            latitude: 0,
            longitude: 0,
            address: ''
        };
        // 选择城市
        AMapUI.loadUI(['misc/MobiCityPicker'], function(MobiCityPicker) {

            var cityPicker = new MobiCityPicker({
                topGroups: [{
                    //组的唯一标识
                    id: 'common_city',
                    //标题
                    title: '常用城市',
                    //右侧锚点索引标题，建议单个字符
                    anchorTitle: '常',
                    //城市的adcodes列表(adcodes内容可以用MobiCityPicker.getCityData()获取)
                    adcodes: [
                        "110000",
                        "310000",
                        "440300",
                        "440100",
                        "510100",
                        "330100",
                        "320500",
                        "500000",
                        "420100",
                        "610100",
                        "320100",
                        "120000"
                    ]
                }, {
                    //组的唯一标识
                    id: 'common_city',
                    //标题
                    title: '推荐城市',
                    //右侧锚点索引标题，建议单个字符
                    anchorTitle: '荐',
                    //城市的adcodes列表(adcodes内容可以用MobiCityPicker.getCityData()获取)
                    adcodes: [
                        "110000",
                        "310000",
                        "120000"
                    ]
                }]
            });

            cityPickerReady(cityPicker);

            // cityPicker.show();
        });
        // 获取中心点
        const getCenter = () => {
            return new Promise(function(resolve, reject) {
                //地图开始 定位
                AMap.plugin('AMap.Geolocation', function() {

                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, //是否使用高精度定位，默认:true
                        timeout: 10000, //超过10秒后停止定位，默认：无穷大
                        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                        showButton: false, //显示定位按钮，默认：true
                        showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                        //offset: [15, 150],//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        position: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
                    });
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition(function(status, result) {
                        if (status == 'complete') {

                            mapInfo.longitude = result.position.lng;
                            mapInfo.latitude = result.position.lat;
                            mapInfo.address = result.formattedAddress;
                            // console.log(center); // center [ll9.2323,39.89797]传入回显定位
                            console.log(mapInfo.address)
                            map.setCenter([mapInfo.longitude, mapInfo.latitude]);
                            resolve(mapInfo)
                        } else {
                            if (center != '') {
                                map.setCenter(center)
                            }
                            console.log('失败原因排查信息:' + result.message);
                        }
                    });
                    document.querySelector(".user-postion").addEventListener("click", function(e) {
                        console.log(1)
                        geolocation.getCurrentPosition()
                    })

                });
            })
        }


        function logMapBounds() {
            var bounds = map.getBounds();
            // 范围
            return {
                northeast: bounds.northeast.toString(),
                southwest: bounds.southwest.toString()
            }
        }
        getCenter().then(res => {
            console.log(res)
        })
        logMapBounds()
            //绑定地图移动与缩放事件
        map.on('moveend', logMapBounds);
        map.on('zoomend', logMapBounds);
        map.on('click', function(ev) {
            // 触发事件的对象
            var target = ev.target;
            console.log(target)
        });
        // 地图拖拽
        AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {

            var positionPicker = new PositionPicker({
                mode: 'dragMap', //dragMap：拖拽地图，dragMarker：拖拽点
                map: map,
                iconStyle: { //自定义外观
                    url: './img/1.png',
                    ancher: [32, 50],
                    size: [32, 25]
                }
            });

            positionPicker.on('success', function(positionResult) {
                // 获取范围
                mapInfo = {
                    latitude: positionResult.position.lat,
                    longitude: positionResult.position.lng,
                    address: positionResult.regeocode.formattedAddress,
                    province: positionResult.regeocode.addressComponent.province,
                    city: positionResult.regeocode.addressComponent.city,
                    district: positionResult.regeocode.addressComponent.district,
                    country: positionResult.regeocode.addressComponent.country,
                    street: positionResult.regeocode.addressComponent.street,
                    township: positionResult.regeocode.addressComponent.township,
                    streetNumber: positionResult.regeocode.addressComponent.streetNumber,
                };
                localStorage.setItem("userAddr", JSON.stringify(mapInfo.address))
                    // console.log(mapInfo, positionResult)
                console.log(logMapBounds())
                document.querySelector(".changeCity").innerHTML = mapInfo.city ? mapInfo.city : mapInfo.province ? mapInfo.province : "";
            });
            positionPicker.on('fail', function(positionResult) {
                console.log("fail")
                    // document.getElementById('address').innerHTML = ' ';
            });
            positionPicker.start();
        });
        // 搜索
        AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

            const poiPicker = new PoiPicker({
                input: 'search'
            });

            //初始化poiPicker
            poiPicker.on('poiPicked', function(poiResult) {
                console.log("搜索事件点击执行")
                const item = poiResult.item;
                mapInfo = {
                    latitude: item.location.lat,
                    longitude: item.location.lng,
                    address: item.district + ' ' + item.name + ' ' + item.address
                };
                console.log(poiResult)
                map.setCenter([item.location.lng, item.location.lat]);

                $('#search').val('');
            });
        });
        inputSearch("#search")
    </script>
</body>

</html>